package com.fantasy.demo1.controller;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/security")
public class SecurityController {

    private UserDetailsService userDetailsService;

    @GetMapping("/hello")
    String home() {
        return "hello, spring security!";
    }

    @RequestMapping("/product/info")
    public String productInfo() {
        String currentUser = "";
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof UserDetails) {
            currentUser = ((UserDetails)principal).getUsername();
        } else {
            currentUser = principal.toString();
        }
        return " some product info, currentUser is:" + currentUser;
    }

    @RequestMapping("/product/home")
    public String productInfo1() {
        return " admin home page";
    }


    @RequestMapping("/login")
    public String loginUser() {
        userDetailsService.loadUserByUsername("1");
        return "fantasy";
    }
}
